/**
 * @description API配置控制器
 * @author 韩
 */

const dayjs = require("dayjs");
const APICONFIG = require("../model/apiconfig-model")
const { getFilter } = require("../utils/setFilter")

// 添加记录
const addRecord = async ({
    createDate = dayjs(),
    title = null, config = Object, status = Number
}) => {
    const params = {
        createDate: createDate,
        title, config, status
    }
    let addRes = null;
    // 添加创建
    addRes = await APICONFIG.create({
        ...params
    })

    if (addRes) {
        return {
            status: "0000",
            message: "成功",
        }
    }
    return {
        status: "2000",
        message: "失败",
    }
}

// 查询列表 
const queryList = async ({ title = null, }) => {
    let filter = {
        title: title && { $regex: eval("/" + title + "/i") },
    }
    filter = getFilter(filter)
    const res = await APICONFIG.find(filter).sort({ createDate: -1 })
    return res;
}

// // 根据id查详情
const getReacdDetail = async ({ _id }) => {
    const res = await APICONFIG.findOne({
        _id
    })
    if (res) {
        const { _id, pageTitle, ip, path, createDate } = res;
        return {
            status: "0000",
            message: "查询成功",
            data: {
                _id: _id, pageTitle, ip, path, createDate
            }
        }
    } else {
        return {
            status: '0001',
            message: "专题详情获取失败"
        }
    }
}

// 更新
const updateRecord = async ({ _id, config, title, status }) => {
    try {
        const query = { _id: _id };
        const updateDoc = {
            $set: {
                status: status,
                title: title,
                config: config
            }
        };
        const res = await APICONFIG.findOneAndUpdate(
            query, updateDoc, { returnDocument: 'after' } //返回更新后的文档
        );

        return {
            status: "0000",
            message: "更新成功",
            data: {
                _id: res._id,
                createDate: res.createDate,
                title: res.title,
                config: res.config,
                status: res.status
            }
        }
    } catch (error) {
        console.log("控制器错误", error);
        return {
            status: "0010",
            message: "服务器出错了"
        }
    }
}

// // 删除
// const deltetUVLOG = async ({ _id }) => {
//     const res = await ARTICLE.findByIdAndDelete({ _id })
//     console.log("删除成功", res);
//     return {
//         status: '0000',
//         message: "删除成功"
//     }
// }
module.exports = {
    addRecord, queryList, updateRecord
}